package cn.wolfcode.p2p.base.util;

import cn.wolfcode.p2p.base.VerifyCode;
import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.domain.UserInfo;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public abstract class UserContext {

    public static final String USER_IN_SESSION = "loginInfo";

    public static final String VERIFCODE_IN_SESSION = "verifyCode";

    public static final String USERINFOR_IN_SESSION = "userInfo";

    public static HttpServletRequest getRequest(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.
                getRequestAttributes()).getRequest();
        /*HttpServletRequest request = MyRequestContextHolder.getRequestMethod();*/
        return request;
    }

    //设置当前用户
    public static void setCurrent(LoginInfo current){
        getRequest().getSession().setAttribute(USER_IN_SESSION,current);
    }

    //获取当前用户
    public static LoginInfo getCurrent(){
        return (LoginInfo) getRequest().getSession().getAttribute(USER_IN_SESSION);
    }

    //设置当前的校验信息对象 到session中
    public static void setVerifCode(VerifyCode vo){
        getRequest().getSession().setAttribute(VERIFCODE_IN_SESSION,vo);
    }

    //从session中获取当前的校验信息对象
    public static VerifyCode getVerifyCode(){
        return (VerifyCode) getRequest().getSession().getAttribute(VERIFCODE_IN_SESSION);
    }

    /**
     * 获取当前的登陆的IP
     * @return 返回当前的IP地址
     */
    public static String getIp() {
        return getRequest().getRemoteAddr();
    }

    public static void setUserInfoCurrent(UserInfo current){
        getRequest().getSession().setAttribute(USERINFOR_IN_SESSION,current);
    }

    public static UserInfo getUserInfoCurrent(){
        return (UserInfo) getRequest().getSession().getAttribute(USERINFOR_IN_SESSION);
    }
}
